<?php
namespace app\common\widgets;
/**
 * 分页工具类
 *
 * 示例
 *
 * 示例1：普通调用
 * <?=Pager::model(array('count'=>1000))->show()?>;
 *
 * 示例2：自定义页面显示大小,当前页now
 * <?=Pager::model(array('count'=>1000,'size'=>15,'now'=>12))->show()?>;
 *
 * 示例3：自定义URL 地址
 * <?=Pager::model(array('count'=>1000),'user/index')->show()?>;
 * user/index 分页类自动会调用Core::createUrl() 函数格式化URL
 *
 * 示例4：调用自定义模板Admin
 * 操作步骤:
 * 1、在分页类定义getAdminData 获取分页数据
 * 2、在分页类定义getAdminHtml 获取HTMl
 * <?=Pager::model(array('count'=>1000))->show('Admin')?>;
 *
 * 示例5：配置其他参数
 * $options = array(
 * 	   'data'=>'all',//all:从$_REQUEST 获取参数,GET:从$_GET 获取参数,POST:从POST 获取参数,如果值数组，则表示自定义数组
 * 	   'filter'=>'aid,name',//过滤掉的参数，多个参数以逗号隔开
 *     'inc'=>'id',//保留的参数,如果inc 有值，则filter 失效
 * );
 *
 * <?=Pager::model(array('count'=>1000))->show($options)?>;
 * 或
 * <?=Pager::model(array('count'=>1000))->show('Admin',$options)?>;
 *
 *
 * Class Page
 */
class Page {

    public $firstRows;  //起始行数
    public $listRows;  //每页显示的行数
    private $parameter;  //页面跳转时需要附带的参数
    private $countPages;  //总页数
    private $countRows;  //总行数
    private $thisPage;  //当前显示的页数
    private $coolPages;  //分页栏的个数
    private $rollPage;  //分页栏每次显示的页数
    private $pageKey;  //接收分页页数的数组下标
    private $url;   //分页链接的url
    private $options;     //配置信息
    private $anchor = '';        //锚点

    /**
     * 静态方法实例化Page对象
     * @return Page
     */

    static public function model() {
        $args = func_get_args();
        $page = new Page();
        call_user_func_array(array($page, 'init'), $args);
        return $page;
    }

    /**
     * 初始化分页数据
     * @param array $page 分页配置
     * $page = array(
     *    'count'=>100,//总记录数量
     *    'size'=>'15',//每页显示记录数 默认 15
     *    'key'=>'page',//分页参数名称 默认page
     * 	  'roll'=>2 //数字页长度
     * )
     * @param string $url  URL 地址，支持以下几种格式
     * $url:/user/index/aid/251 不建议使用这个种格式
     * $url:/user/index?aid=251
     */
    public function init($page = array(), $url = '') {
        //$countRows, $listRows = 20, $parameter = '', $rollPage = 10, $pageKey = 'p'
        $this->countRows = $page['count'];  //总记录数
        $this->listRows = !empty($page['size']) ? $page['size'] : 15;  //每页显示的行数
        $this->parameter = null;  //页面跳转时需要带的参数
        $this->url = $url; //分页地址
        $this->rollPage = !empty($page['roll']) ? $page['roll'] : 10;  //分页栏每次显示的链接个数，默认为10个
        $this->countPages = ceil($this->countRows / $this->listRows); //总页数
        $this->coolPages = ceil($this->countPages / $this->rollPage); //分页栏个数
        $this->pageKey = !empty($page['key']) ? $page['key'] : 'page';
        $this->anchor = !empty($page['anchor']) ? $page['anchor'] : '';
        //计算当前页
        if (!empty($page['now'])) {
            $this->thisPage = $page['now'];
        } else {

            if (!empty($_REQUEST[$this->pageKey])) {
                $this->thisPage = $_REQUEST[$this->pageKey]; //如果指定显示的页面
            } else {
                $this->thisPage = 1; //如果未指定显示的页面
            }
        }

        $this->firstRows = $this->listRows * ($this->thisPage - 1); //计算忽略行数
    }

    /**
     * 生成链接url
     * @return string
     */
    private function url() {

        $params = array();
        $base_url = empty($this->url) ? $_SERVER['REQUEST_URI'] : $this->url; //基础路径
        //获取?参数
        $parse = parse_url($base_url);
        if (isset($parse['query'])) {
            parse_str($parse['query'], $params);
        }

        if (isset($parse['fragment'])) { // 解析锚点
            $this->anchor = $parse['fragment'];
        }

        //参数源-合并参数
        $options = $this->options;
        if (empty($options['data']) || $options = 'all') {//$_REQUEST 参数
            $params = array_merge($_REQUEST, $params);
        } else if ($options['data'] == 'GET') {
            $params = array_merge($_GET, $params);
        } else if ($options['data'] == 'POST') {
            $params = array_merge($_POST, $params);
        } else if (is_array($options['data'])) {
            $params = $options['data'];
        }

        //过滤分页参数值
        unset($params[$this->pageKey]);

        //过滤参数
        if (!empty($this->options['inc'])) {
            $params_arr = array(); //
            $inc = $this->options['inc'];
            foreach ($inc as $key) {
                if (isset($params[$key])) {
                    $params_arr[$key] = $params[$key];
                }
            }

            $params = $params_arr;
        } else {
            if (!empty($this->options['filter'])) {
                $filter = explode(',', $this->options['filter']);
                foreach ($filter as $key) {
                    unset($params[$key]);
                }
            }
        }

        if (empty($params)) {
            $url = $parse['path'] . '?' . $this->pageKey . '=';
        } else {
            $url = $parse['path'] . '?' . http_build_query($params) . '&' . $this->pageKey . '=';
        }

        return $url;
    }

    /**
     * 获取最终的分页HTML
     * @param string $style 模板名称
     * @param array $otpions 配置参数
     * @return string  如果总页码小2，则返回空
     */
    public function show($style = 'Page', $otpions = array()) {

        if (is_array($style)) {
            $this->otpions = $style;
        } else {
            if (empty($style)) {
                $style = 'Page';
            }
        }

        //生成地址
        $url = $this->url();

        $fun_data = 'getPageData';
        $fun_html = 'get' . $style . 'Html';
        $page = $this->$fun_data();
        $page['url'] = $url;
        $html = $this->$fun_html($page);
        return $html;
    }

    /**
     * 计算Page模板分页数据
     * @return array
     */
    public function getPageData() {
        $page = array();
        //计算尾页
        $page['last'] = $this->countPages;
        //计算下一页
        $page['next'] = ($this->thisPage + 1 ) > $this->countPages ? $this->countPages : $this->thisPage + 1;
        //计算上一页
        $page['pre'] = ($this->thisPage - 1 ) < 1 ? 1 : $this->thisPage - 1;
        //首页
        $page['index'] = 1;
        //尾页
        $page['end'] = $this->countPages;
        //当前页
        $page['now'] = $this->thisPage;
        //总页码
        $page['countPage'] = $this->countPages;
        $mid_area_num = 2;
        $num = array();
        $ellipsis_str = "...";

        /**
         * 计算数字页
         * */
        $num['index'] = $page['index'];
        //特殊需求，当省略号部分只有1个页码时，不显示... 直接显示页码
        if ($page['now'] - 1 == $mid_area_num + 2)
            $num[2] = 2;
        else if ($page['now'] - 1 > $mid_area_num + 2)
            $num['p'] = $ellipsis_str;

        for ($i = max($page['now'] - $mid_area_num, 2); $i <= $page['now']; $i++) {
            $num[$i] = $i;
        }

        for ($i = $page['now'] + 1; $i < min($page['now'] + $mid_area_num + 1, $page['countPage']); $i++) {
            $num[$i] = $i;
        }

        //特殊需求，当省略号部分只有1个页码时，不显示... 直接显示页码
        if ($page['countPage'] - $page['now'] == $mid_area_num + 2)
            $num[$page['countPage'] - 1] = $page['countPage'] - 1;
        else if ($page['countPage'] - $page['now'] > $mid_area_num + 2)
            $num['a'] = $ellipsis_str;

        $num[$page['last']] = $page['last'];
        $page['num'] = $num;
//        echo "<pre>";print_r($page);exit;
        return $page;
    }

    /**
     * 获取Page模板分页HTML
     * @param array $page 分页数据 由getPageData 生成
     */
    public function getPageHtml($page = array()) {
        $html = '<div class="col-sm-4 text-right text-center-xs"><ul class="pagination pagination-sm m-t-none m-b-none">';
        $anchor = '';
        if (!empty($this->anchor)) {
            $anchor = '#' . $this->anchor;
        }

        //上一页
        if ($page['now'] > 1) {
            $html .= '<li><a href="' . $page['url'] . $page['pre'] . $anchor . '"><i class="fa fa-chevron-left"></i></a></li>';
        }

        //数字页
        foreach ($page['num'] as $num) {
            if ($num == '...') {
                $html .= '<li><a  href="javascript:void(0);">' . $num . '</a></li>';
                continue;
            }

            if ($num == $page['now']) {
                $html .= '<li><a href="javascript:void(0);" class="disabled" style="color: #545a5f;background-color:transparent;">' . $num . '</a></li>';
            } else {
                $html .= '<li><a  href="' . $page['url'] . $num . $anchor . '">' . $num . '</a></li>';
            }
        }

        //下一页
        if ($page['next'] < $page['countPage']) {
            $html .= '<li><a href="' . $page['url'] . $page['next'] . $anchor . '"><i class="fa fa-chevron-right"></i></a></li>';
        }

        $html .= '</ul></div>';
        return $html;
    }

    public function getNewPageHtml($page =  []) {
        $html = '<ul class="pagination pagination-sm m-t-sm m-b-none" data-apages-total="'.$page['countPage'].'" data-apage-current="'.$page['now'].'">';
        $anchor = '';
        if (!empty($this->anchor)) {
            $anchor = '#' . $this->anchor;
        }

        $html .= '<li ';
        if($page['now'] == 1) {
            $html .= ' class="disabled" ';
        }
        $html .= '>';
        $html .= '<a href="javascript:;" rel="first" data-page-num="1"><i class="fa fa-angle-double-left" title="第一页"></i></a></li>';

        $html .= '<li ';
        if($page['now'] == 1) {
            $html .= ' class="disabled" ';
        }
        $html .= '>';
        $html .= '<a href="javascript:;" rel="prev" data-page-num="' . ($page['now'] - 1) . '"><i class="fa fa-angle-left" title="上一页"></i></a></li>';
        //数字页
        for($i = 1; $i <= $page['countPage']; $i ++) {
            if ($i == $page['now']) {
                $html .= '<li class="active"><a href="javascript:void(0);"  data-page-num="'.$i.'" data-page-isnum="true">' . $i . '</a></li>';
            } else {
                $html .= '<li><a  href="' . $page['url'] . $i . $anchor . '">' . $i . '</a></li>';
            }
        }
        $html .= '<li ';
        if($page['now'] == $page['countPage']) {
            $html .= ' class="disabled" ';
        }
        $html .= '>';
        $html .= '<a href="javascript:;" rel="next" data-page-num="' .($page['now'] + 1) .'"><i class="fa fa-angle-right" title="下一页"></i></a></li>';
        $html .= '<li ';
        if($page['now'] == $page['countPage']) {
            $html .= ' class="disabled" ';
        }
        $html .= '>';
        $html .= '<a href="javascript:;" rel="last" data-page-num="'.$page['countPage'].'"><i class="fa fa-angle-double-right" title="最后页" ></i></a></li>';
        $html .= '</ul>';
        return $html;
    }
}
